<?php
/**
 * Abstraktna trieda Page je predkom vsetkych zobrazitelnych stranok
 *
 */
abstract class Page {

	public $admin;
	public $menu_positions;

	/**
     * Premenna reprezentujuca instanciu PHP Smarty sablony
     *
     * @var Smarty
     */
	protected $tpl;

	/**
     * Konstruktor triedy
     *
     * Posle potrebne premenne do sablony,
     * vygeneruje linky pre jazyky,
     * skontroluje prava a prihlasenie,
     * nastavi zaklad "cesty",
     * vytvori zoznam moznych pozicii menu
     *
     * @global $r globalna stavova premenna
     * @global $db globalna premenna reprezentujuca spojenie s databazou
     */
	public function __construct() {
		global $r,$db;

		//inicializacia sablonovacieho systemu
		$this->initSmarty();


		// lokalizacia
		if ($r["i18n"]["enabled"]) {

			$r["admin_lang"] = $_SESSION["user"]["lang"] ? $_SESSION["user"]["lang"] : $this->cfg["admin_lang"];
     		$this->tpl->assign("adminLang",     $r["admin_lang"]);
			$this->tpl->assign("lang",          $r["lang"]);

			/**
             * vygenerovanie liniek na zmenu odkazu do pola $languages
             * a jeho poslanie na sablonu
             */
			$action = implode("/", $r["arg"]);
			$languages = array();

			foreach ($r["i18n"]["languages"] as $lang => $language) {

				/*$tmp = $r["arg"];
				if ($tmp[0]=="content") {
					$id=$db->getCell("SELECT id FROM content WHERE alias='{$tmp[1]}' AND lang='{$r[lang]}'");
					if ($id) {
						$tmp[1] = $db->getCell("SELECT alias FROM content WHERE id='{$id}' AND lang='{$lang}'");
						$action = implode("/", $tmp);
					}
				}*/

				$languages[$lang] = array(
				"name" => $language,
				"link" => rA("$lang", true)
				);
			}
			//rPrint($languages);

			$this->tpl->assign("languages", $languages);
		}


		// prihlasovanie uzivatelov
		if ($_SESSION["timeout"] > time() - $this->cfg["session_timeout"])  { //ak nevyprsal cas
			if ($_SESSION["user"])   $this->tpl->assign("user",   $_SESSION["user"]);

			if (is_array($_SESSION["access"])) {
				$this->tpl->assign("access", $_SESSION["access"]);
			}

			$_SESSION["timeout"] = time();

			// vyprsanie session
		} else {
			User::logout(); // odhlasenie
		}


		// zaklad pre csetu
		//$this->path = array(array("", "sk" => "Domov", "en" => "Home"));
		$this->path = array(array("", i18n::t("home")));


		// mozne pozicie menu
		$this->menu_positions = array(
		"side" => array(
		"admin" => true,
		"sk"    => "Bočné menu",
		"en"    => "Side Menu"
		)/*
		"top" => array(
		"admin" => true,
		"sk"    => "Horné menu",
		"en"    => "Top Menu"
		)*/

		);
		$this->tpl->assign("menu_positions", $this->menu_positions);

	}


	/**
     * Metoda volana pred zobrazenim stranky
     *
     * Priradi do sablony premenne, ktore menili potomkovia,
     * nacita menu
     *
     * @global $r globalna stavova premenna
     * @global $db globalna premenna reprezentujuca spojenie s databazou
     *
     */


	/**
     * Metoda na oznamenie chyboveho stavu uzivatelovi (neopravneny pristup a pod.)
     *
     * @param string $title nazov stavu
     * @param string $text text stavu
     */
	protected function status($title, $text) {
		$this->tpl->assign("statusTitle", $title);
		$this->tpl->assign("status", $text);
		$this->tpl->assign("path", $this->path);
		$this->tpl->display("status.tpl");
	}


	/**
     * Metoda na zistenie pristupovych prav.
     *
     * Zistuje ci je uzivatel nalogovany a ma dostatocne prava.
     *
     * @param string $type typ prav uzivatela
     * @param boolean $message urcuje, ci ma byt v pridae neuspechu zobrazene chybove hlasenie
     * @param boolean/string $redirect urcuje, ci/kam ma byt uzivatel v pripade neuspechu presmerovany
     * @return boolean uzivatel je prihlaseny a ma prava
     */
	protected function checkAccess($type, $message = false, $redirect = false) {
		global $r;


		if ($_SESSION["access"][$type]) { //prihlasenie je ulozene v sessions
			return true; //uspech - uzivatel je prihlaseny
		} else {
			if ($redirect) { // ak ma byt presmerovany
				if (is_string($redirect))
				rLocate($redirect); // presmerovanie na danu adresu
				else
				rLocate($r["lang"]); //presmerovanie na uvod

			} elseif ($message) { //ak ma byt zobrazene chybove hlasenie
				$this->status(
				i18n::t("msg_access2"),
				i18n::t("msg_access")
				);
			}
			return false; //neuspech - uzivatel nie je prihlaseny
		}
	}


	/**
     * Metoda na nacitanie navigacneho menu
     *
     */
	private function loadMenu() {
		global $db, $r;

		$tree = new rTree("menu", "id", "parent_id"); // vytvorenie stromu menu
		$menu = array();

		foreach ($this->menu_positions as $position => $info) { //pre vsetky menu - hlavne a bocne

			$tree->setQuery("tree", "
                SELECT t1.%ID%, t1.title, t1.link, t1.target, COUNT(t2.%ID%) AS count
                FROM %TABLE% t1
                LEFT JOIN %TABLE% t2
                   ON t2.%PARENT_ID% = t1.%ID%
                  AND t2.lang = '{$r["lang"]}'
                WHERE t1.%PARENT_ID% = %d
                  AND t1.menu = '$position'
                  AND t1.lang = '{$r["lang"]}'
                GROUP BY t1.%ID%, t1.weight, t1.title, t1.link, t1.target
                ORDER BY t1.weight, t1.%ID%
            "); // vygerovanie menu stromu

			 $tree->setQuery("path", "
                SELECT * FROM %TABLE%
                WHERE %ID% = %d
            "); // vygenerovanie path


      $this->active_menu=$nodes[$i][id]= $r[arg][1];

			$nodes = $tree->getMultiTree(0, $this->active_menu + 0,true); // ziskanie menu zo stromu



			$this->menu_html = "";
			$this->generateListMenu($nodes); // vygenerovanie menu v html a priradenie do $this->menu_html

			$menu[$position] = $this->menu_html; // priradenie menu spravnej pozicii
		}

		$this->tpl->assign("menu", $menu); // poslanie menu na sablonu
	}

	/**
     * Metoda, ktora sa stara o vygenerovanie blokov
     *
     * Vygenerovane bloky posiela priamo na sablonu
     */
	private function loadBlocks() {
		global $db, $r;

		$blocks = $db->getArrRow("
            SELECT * FROM blocks
            WHERE lang = '{$r["lang"]}'
            ORDER BY weight
        ");

		foreach ($blocks as &$msg) {

			$this->cleanUrl($msg[text]); //prevod odkazov
		}

		$this->tpl->assign("blocks", $blocks);
	}

	/**
     * Metoda na zobrazenie prvych N noviniek na stranke
     *
     * Pocet noviniek zodpoveda hodnote news_main v konfiguracnom subore
     *
     */
	private function loadNews() {
		global $db, $r;

		$count = $this->cfg["news_main"];

		$news = $db->getArrRow("
            SELECT *, to_char(date, 'DD.MM.YYYY') AS d  FROM news
            WHERE lang = '{$r["lang"]}'
            ORDER BY date DESC
            LIMIT '$count'
        ");

		foreach ($news as &$msg) {

			$this->cleanUrl($msg[text]); //prevod odkazov
		}

		$this->tpl->assign("news", $news);
	}


	/**
     * Metoda, ktora sa stara o vygenerovanie menu
     *
     * @param array $nodes polozky menu
     * @return string vygenerovane menu
     *
     * @global $r globalna stavova premenna
     */
	private function generateListMenu($nodes) {
		global $r,$db;

		$this->menu_html .= "<ul id=\"menu\">"; // zaciatok zoznamu

		foreach ((array)$nodes as $node) { // pre kazdu polozku menu

			if (strstr($node["link"],"content/")) {
				$tmp = explode("/",$node["link"]);
				if (is_numeric($tmp[1])) {
					$node["link"] = "content/".$db->getCell("SELECT alias FROM content WHERE id='{$tmp[1]}' AND lang='{$r[lang]}'");
				}
			}

			if (!empty($node["target"])) //odkay sa otvara v novom okne
				$target=" target=\"{$node["target"]}\"";

			// jedna polozka
			$this->menu_html .= "<li><a" .
			($this->active_menu == $node["id"] ? " class=\"menuitem selected\"" : " class=\"menuitem\"") .
			" href=\"" . rUrl($node["link"]) . "\" $target>{$node["title"]}</a>";

			if (count($node["children"])) //ak ma polozka podpolozku
			$this->generateListMenu($node["children"]); // vygeneruj podmenu

			$this->menu_html .= "</li>\n";
		}

		$this->menu_html .= "</ul>\n"; //koniec zoznamu

		return $this->menu_html;
	}     
	




	/**
     * Metoda na upload obrazka
     *
     * @param integer $id id obrazka z fromulara
     * @param string $dir adresar kam ma byt pbtazok umiestneny
     * @param string $file_name nazov suboru
     * @param boolean $resize priznak ci ma byt obrazku zmenena velkost
     * @param string $size prefix polozky v konfiguracnom subore urcujuci velkost
     * @param boolean $thumb priznak ci ma byt cygenerovana aj miniatura
     * @param string $newName nove meno suboru
     * @return boolean priznak, ci bola operacia uspesna
     */
	public function uploadPhoto($id, $dir, $file_name = null,
	$resize = true, $size = "inset_images", $thumb = true, &$name) {

		global $db, $r;



		if (($_FILES["image"]["error"][$id] == 0) && ($_FILES["image"]["size"][$id])) { // ak nie su ziadne chyby v uploade

			$ext  = eregi_replace('(.*)\.([a-zA-Z0-9]{2,4})$', '\\2', $_FILES["image"]["name"][$id]); // zisti priponu

			if (!in_array($ext, array("jpg", "jpeg", "gif", "JPG")))
			return false; //ak nejde o podporovany typ

			str_replace("JPG","jpg",$ext);

			if ($file_name) { //ak je zadane meno
				$name = $file_name;
			} else { //ak nie je zadane meno
				$name = eregi_replace('\.jpg$', "", $_FILES["image"]["name"][$id]); // vytvor meno z id
				$name = eregi_replace('\.gif$', "", $name);
				$name = eregi_replace('/',      "", $name);
				$name = eregi_replace('^\.*',   "", $name);
			}

			$tmp = $_FILES["image"]["tmp_name"][$id]; // vytvorenie docasneho suboru

			$suffix = ""; $i = 0;
			while (file_exists("$dir/$name$suffix.$ext")) { //ak uz subor existuje prida sa cislo
				$i++; $suffix = "-$i";
			}
			$name .= $suffix;

			list($tmp_w, $tmp_h) = getimagesize($tmp); //rozmery obrazka
			$img_size = $this->cfg["{$size}_size"]; // pozadovany rozmer z konfiguracneho suboru podla parametra

			if ($thumb) { // vytvorenie miniatury a prava
				rGraphics::imgResize($tmp, "$dir/$name-thumb.$ext", $this->cfg["{$size}_thumb_size"]);
				chmod("$dir/$name-thumb.$ext", 0644);
			}

			if (($resize) && (($tmp_w > $img_size) || ($tmp_h > $img_size))) { //ak ma byt obrazok zmenseny a je vcasi ako treba
				rGraphics::imgResize($tmp, "$dir/$name.$ext", $this->cfg["{$size}_size"]);
			} else {
				rename($tmp, "$dir/$name.$ext"); //inac sa len skopiruje
			}

			chmod("$dir/$name.$ext", 0644); // prava pre uplaodnuty subor

			return true; //operacia uspesna

		} else { //ak sa vyskytuju chyby
			$errList = array(
			0                   => "nevybrali ste súbor",
			UPLOAD_ERR_INI_SIZE => "príliš veľký súbor",
			UPLOAD_ERR_PARTIAL  => "nepodarilo sa nahrať celý súbor",
			UPLOAD_ERR_NO_FILE  => "nevybrali ste súbor"
			);

			return false; //operacia neuspesna
		}
	}

	 /*
	  * Metoda na hromadny upload suborov z formulara
	  *
	  * @param array $postArray pole s uploadnutymi subormi
	  * @param string $dir cielovy adresar
	  */
	 public static function uploadAllFiles($postArray, $dir) {

        if (!is_dir($dir)) {
            mkdir($dir);
            chmod($dir,777);
        }

        for ($i = 0; $i < count($_FILES[$postArray]["tmp_name"]); $i++) {
            if ($_FILES[$postArray]["tmp_name"][$i]) {

                //$target = $dir . "/" .$_FILES[$postArray]["name"][$i];

                $ext  = eregi_replace('(.*)\.([a-zA-Z0-9]{2,4})$', '\\2', $_FILES[$postArray]["name"][$i]); // zisti priponu
				$name = eregi_replace('(.*)\.([a-zA-Z0-9]{2,4})$', '\\1', $_FILES[$postArray]["name"][$i]); // zisti priponu

				$tmp = $_FILES[$postArray]["name"][$i]; // vytvorenie docasneho suboru

				$suffix = ""; $i = 0;
				while (file_exists("$dir/$name$suffix.$ext")) { //ak uz subor existuje prida sa cislo
					$i++; $suffix = "-$i";
				}
				$name .= $suffix;

                move_uploaded_file($_FILES[$postArray]["tmp_name"][$i], $dir."/".$name.".".$ext);
            }
        }
    }

	/**
	 * Metoda na inicializaciu sablonovacieho sustemu
	 *
	 */
	private function initSmarty() {
		global $r;

		/**
		 * Vlozenie knzicnice PHP Smarty
		 *
		 *
		 */
		define("SMARTY_DIR", "{$r["smartyPath"]}/");
		require_once(SMARTY_DIR . "Smarty.class.php");

		// instancia smarty
		$this->tpl = new Smarty;

		/* nastavenie premennych podla globalne premennej $r CMS systemu */
		$this->tpl->template_dir = "{$r["root"]}/tpl/";
		$this->tpl->compile_dir  = "{$r["root"]}/tpl/compiled/";
		$this->tpl->config_dir   = "{$r["root"]}/tpl/conf/";
		$this->tpl->cache_dir    = "{$r["root"]}/tpl/cache/";

		//dolezite premmnene pre sablonu
		$this->tpl->assign("gfx",  "{$r["webRoot"]}/gfx/");
		$this->tpl->assign("lib",  "{$r["webRoot"]}/lib/");
		$this->tpl->assign("data", "{$r["webRoot"]}/data/");

		// nacitanie konfiguracneho suboru
		$this->tpl->config_load("setup.conf");
		$this->cfg = $this->tpl->get_config_vars();

		// premenne pouzivane sablonami
		$this->tpl->assign("arg",           $r["arg"]);
		$this->tpl->assign("module",        $r["arg"][0]);
		$this->tpl->assign("url",           implode("/", $r["arg"]));
		$this->tpl->assign("baseUrl",       $r["server"] . $r["webRoot"]);
	}


	/**
	 * Metod na zobrazenie stranky
	 *
	 * Potomkovia ju predefinuvavaju, najprv sa vola metoda finish.
	 *
	 */
	public function show() {

		// nacitanie menu
		$menu = $this->loadMenu();

		//nacitanie blokov
		$this->loadBlocks();

		//nacitanie noviniek
		$this->loadNews();
	}


	/**
	 * Funkcia na prepis odkazov v zadanom texte
	 *
	 * @param string$string text, kde sa maju prepisat URL
	 */
	public static function cleanUrl(&$string) {
        $string = preg_replace_callback('/href="([^"]*)"/', "cleanUrlCallback", $string);
    }






}

	/**
 * Callback funkcia na prepis odkazov v style CMS
 *
 * @param string $arr povodny odkaz
 * @return prepisany odkaz
 */
function cleanUrlCallback($arr) {
	global $r;

	if (strlen(strstr('href="' . rUrl(trim($arr[1], "/")) . '"',"."))>0) {
		return str_replace("/".$r[lang],"",'href="' . rUrl(trim($arr[1], "/")) . '"');
	}
	return 'href="' . rUrl(trim($arr[1], "/")) . '"';
}





?>
